import { getToken, getAuth } from '../utils/account'

const app = getApp()

/** @responseType 数据格式 */
const request = (url, options, needLogin = false, responseType = '') => {
    // wx.showLoading({
    //     title: '正在加载',
    //     mask: true,
    // })
    return new Promise(async (resolve, reject) => {
        const token = await getToken()
        if (needLogin && !token) {
            getAuth()
            return
        }
        wx.request({
            url: `${app.globalData.sglHost}${url}`,
            method: options.method,
            data: options.data,
            responseType: responseType,
            header: {
                'Content-Type': options.method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json; charset=UTF-8;',
                'token': token // 看自己是否需要
            },
            success(request) {
                if (request.data.code === 0) {
                    resolve(request.data)
                } else if (request.data.info === '请求令牌不能为空！') { //无token
                    wx.clearStorageSync()
                    getAuth()
                } else if (request.data.info === 'Undefined index: caliance_club_id') { //token过期
                    wx.showToast({
                        title: '登录已失效',
                        icon: 'none',
                        duration: 2000,
                        success(res) {
                            wx.clearStorageSync()
                        }
                    })
                } else if (request.data.info === '您不是指定身份！') {
                    resolve(request.data)
                }else {
                    setTimeout(() => {
                        wx.showToast({
                            title: request.data.info,
                            icon: 'none',
                        });
                        setTimeout(() => {
                            wx.hideToast();
                        }, 2000)
                    }, 0);
                }
            },
            fail(error) {
                wx.showToast({
                    title: '请求出错',
                    icon: 'none'
                })
                reject(error.data)
            },
            complete(res) {
                // wx.hideLoading();
            }
        })

    }).catch(error => {
        wx.showToast({
            title: '请求出错',
            icon: 'none'
        })
    })
}

const get = (url, options = {}, needLogin = false, ) => {
    return request(url, {
        method: 'GET',
        data: options
    }, needLogin)
}

const post = (url, options, needLogin = false, responseType) => {
    return request(url, {
        method: 'POST',
        data: options
    }, needLogin, responseType)
}


module.exports = {
    get,
    post
}